package com.robotic.test;

import lombok.Data;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;


/**
 * 获取cpu频率和温度
 */
@Data
public class ControllerSafeData {
    private final float[] motorTemperature;
    private final byte[] driverTemperature;
    private final float cpuTemperature;
    private final float cpuFrequency;

    public ControllerSafeData(byte[] data) {
        // The total data payload should be 68 bytes.
        if (data.length < 68) {
            throw new IllegalArgumentException("Invalid data length for ControllerSafeData. Expected 68, got " + data.length);
        }

        ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);

        // 1. Read motor temperatures (12 * 4 = 48 bytes)
        this.motorTemperature = new float[12];
        for (int i = 0; i < 12; i++) {
            this.motorTemperature[i] = buffer.getFloat();
        }

        // 2. Read driver temperatures (12 * 1 = 12 bytes)
        this.driverTemperature = new byte[12];
        buffer.get(this.driverTemperature);

        // 3. Read CpuInfo (4 + 4 = 8 bytes)
        this.cpuTemperature = buffer.getFloat();
        this.cpuFrequency = buffer.getFloat();
    }

    // Manual getter methods to resolve compilation issues
    public float getCpuTemperature() {
        return cpuTemperature;
    }

    public float getCpuFrequency() {
        return cpuFrequency;
    }

    @Override
    public String toString() {
        // Creating a more readable representation for the driver temperatures
        short[] unsignedDriverTemps = new short[12];
        for(int i=0; i < driverTemperature.length; i++) {
            unsignedDriverTemps[i] = (short) Byte.toUnsignedInt(driverTemperature[i]);
        }

        return "ControllerSafeData{" +
                "motorTemperature=" + Arrays.toString(motorTemperature) + "°C" +
                ", driverTemperature=" + Arrays.toString(unsignedDriverTemps) + "°C" +
                ", cpuTemperature=" + cpuTemperature + "°C" +
                ", cpuFrequency=" + cpuFrequency + "MHz" +
                '}';
    }
}
